package cn.tedu.dbinit;

import ch.qos.logback.core.encoder.EchoEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootApplication
public class DbInitApplication {
    @Autowired
    private DataSource dataSource; //默认Hikari
    public static void main(String[] args) {
        SpringApplication.run(DbInitApplication.class, args);
    }
    @PostConstruct//扫描创建完对象会自动执行
    public void runSql() throws SQLException {
        run("sql/account.sql");
        run("sql/order.sql");
        run("sql/seata-server.sql");
        run("sql/storage.sql");
    }
    private void run(String sql) throws SQLException {
        //封装一个资源对象
        ClassPathResource cpr = new ClassPathResource(sql, DbInitApplication.class.getClassLoader());
        EncodedResource res = new EncodedResource(cpr, "UTF-8");
        ScriptUtils.executeSqlScript(dataSource.getConnection(), res);
    }

}
